package com.thinksns.sociax.t4.android.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.thinksns.sociax.android.R;
import com.thinksns.sociax.t4.adapter.AdapterUserFollowingListNew;
import com.thinksns.sociax.t4.android.Thinksns;
import com.thinksns.sociax.t4.android.data.StaticInApp;
import com.thinksns.sociax.t4.android.presenter.NearByUserPresenter;
import com.thinksns.sociax.t4.android.user.ActivityUserInfo_2;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.model.ModelSearchUser;
import com.thinksns.sociax.t4.model.ModelUser;
import com.thinksns.sociax.thinksnsbase.base.BaseListFragment;
import com.thinksns.sociax.thinksnsbase.base.ListBaseAdapter;
import com.thinksns.sociax.thinksnsbase.bean.ListData;
import com.thinksns.sociax.thinksnsbase.utils.ActivityStack;

/**
 * 类说明： 附近的人
 * @author hedong
 * @version 1.0
 * @date 2016.3.1
 */
public class FragmentFindPeopleNearBy extends BaseListFragment<ModelSearchUser>
        implements AMapLocationListener{
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private BroadcastReceiver mUpdateFollowRecevier;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initOptions();
    }

    /**
     * 初始化定位参数
     */
    public void initOptions() {
        locationClient = new AMapLocationClient(getActivity().getApplicationContext());
        locationOption = new AMapLocationClientOption();
        // 设置定位模式为高精度模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        locationOption.setOnceLocation(true);
        // 设置定位监听
        locationClient.setLocationListener(this);

        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    @Override
    protected void initPresenter() {
        //自定义实现附近的人Presenter
        mPresenter = new NearByUserPresenter(getActivity(), this);
        mPresenter.setCacheKey("nearby_user");
    }

    @Override
    public void onDestroy() {
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
        getActivity().unregisterReceiver(mUpdateFollowRecevier);
        super.onDestroy();
    }

    @Override
    protected void initReceiver() {
        super.initReceiver();
        mUpdateFollowRecevier = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                // 对某用户关注/取消关注后触发的
                if (action.equals(StaticInApp.NOTIFY_FOLLOW_USER)) {
                    int uid = intent.getIntExtra("uid", 0);
                    int follow = intent.getIntExtra("follow", 0);
                    if (uid > 0) {
                        updateUserFollow(uid, follow);
                    }
                }
            }
        };

        IntentFilter intentFilter = new IntentFilter(StaticInApp.NOTIFY_FOLLOW_USER);
        if (intentFilter != null) {
            getActivity().registerReceiver(mUpdateFollowRecevier, intentFilter);
        }
    }

    @Override
    protected boolean requestDataIfViewCreated() {
        return false;
    }

    @Override
    protected ListBaseAdapter<ModelSearchUser> getListAdapter() {
        return new AdapterUserFollowingListNew(getActivity()) {
            @Override
            public int getMaxId() {
                if(mDatas == null || mDatas.size() == 0)
                    return 0;
                return ((ModelSearchUser)mDatas.get(mDatas.size() -1)).getUid();
            }
        };
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ModelSearchUser modelSearchUser = (ModelSearchUser) mAdapter.getItem((int) id);
        if(modelSearchUser != null) {
            if (Thinksns.getMy().getUid() != modelSearchUser.getUid() && ModelUser.CAN_NOT_TO_HOME == modelSearchUser.getSpace_privacy()){
                ToastUtils.showToast(R.string.tip_no_oauth_to_other_home);
            }else {
                Bundle bundle = new Bundle();
                bundle.putInt("uid", modelSearchUser.getUid());
                ActivityStack.startActivity(getActivity(), ActivityUserInfo_2.class, bundle);
            }
        }
    }

    @Override
    public void onLoadDataSuccess(ListData<ModelSearchUser> data) {
        mEmptyLayout.setNoDataContent(getResources().getString(R.string.empty_user));
        super.onLoadDataSuccess(data);
        // 当前页数大于总页数，设置只能下拉刷新 7.31.2017 by Lei
        if (mPresenter.getMaxId() >= ((NearByUserPresenter)mPresenter).getTotalPages()){
            setRefreshMode(BaseListFragment.PULL_FROM_START);
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                ((NearByUserPresenter)mPresenter).setLatitudeLngitude(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                mPresenter.loadInitData(true);
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Toast.makeText(getActivity(), "定位失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 刷新关注、取消关注用户的状态
     *
     * @param following
     */
    private void updateUserFollow(int uid, final int following) {
        for (int i = 0; i < mAdapter.getDataSize(); i++) {
            if (mAdapter.getItem(i).getUid() == uid) {
                    mAdapter.getItem(i).setFollowing(String.valueOf(following));
                break;
            }
        }
        mAdapter.notifyDataSetChanged();
    }
}
